# -*- coding: utf-8 -*-
# author: ChangYuan
# 这个插件向tcp服务器发送起飞指令
import logging
import socket
from robot.sdk.AbstractPlugin import AbstractPlugin
import json
INTENT = "DRONE_TAKE_OFF"

logger = logging.getLogger(__name__)


class Plugin(AbstractPlugin):

    SLUG = "Take off"

    def handle(self, text, parsed):
        try:
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect(("127.0.0.1", 11451))  # 必须是元组
            #json格式化传递参数
            order_dict = {'order_name': 'ORDER_TAKE_OFF', 'order_args': ''}
            json_data = json.dumps(order_dict)
            #order = "ORDER_TAKE_OFF"
            client.send(json_data.encode("utf-8"))
            ##后面需要加入核对机制
            from_server_call_back = client.recv(1024)
            self.say(from_server_call_back, cache=True)
            client.close()

        except Exception as e:
            logger.error(e, stack_info=True)
            self.say("抱歉，TAKE_OFF插件出问题了，请稍后再试", cache=True)

    def isValid(self, text, parsed):
        return self.nlu.hasIntent(parsed, INTENT) or "起飞" in text
